package tools

import (
	"errors"
	"reflect"
)

/**
 * @author ljfirst
 * @version V1.0
 * @date 2023/7/8 01:40
 * @author-Email ljfirst@mail.ustc.edu.cn
 * @blogURL https://blog.csdn.net/ljfirst
 * @description
 * */
func Interface2Int(v interface{}) (int, error) {
	value, ok := v.(int)
	if !ok {
		return 0, errors.New("translate Interface2Int error")
	}
	return value, nil
}

func IntArray2InterfaceArray(array []int) ([]interface{}, error) {
	if len(array) == 0 {
		return []interface{}{}, nil
	}
	ans := make([]interface{}, 0)
	for i := 0; i < len(array); i++ {
		ans = append(ans, array[i])
	}
	return ans, nil
}

func Interface2IntArray(v interface{}) ([]int, error) {
	valueV := reflect.ValueOf(v)
	if valueV.Kind() != reflect.Array && valueV.Kind() != reflect.Slice {
		return nil, errors.New("not array")
	}
	value, ok := v.([]int)
	if ok {
		return value, nil
	}
	valueI, okI := v.([]interface{})
	if !okI {
		return nil, errors.New("translate Interface2IntArray error")
	}
	return InterfaceArray2IntArray(valueI)
}

func InterfaceArray2IntArray(v []interface{}) ([]int, error) {
	if len(v) == 0 {
		return []int{}, nil
	}
	array := make([]int, 0)
	for i := 0; i < len(v); i++ {
		value, ok := v[i].(int)
		if !ok {
			return nil, errors.New("translate InterfaceArray2IntArray error")
		}
		array = append(array, value)
	}
	return array, nil
}
